package com.chinasoft.maysham.manager.service.project.impl;

import com.chinasoft.maysham.manager.exception.BizException;
import com.chinasoft.maysham.manager.model.Project;
import com.chinasoft.maysham.manager.model.ProjectUser;
import com.chinasoft.maysham.manager.model.Role;
import com.chinasoft.maysham.manager.repo.project.ProjectRepo;
import com.chinasoft.maysham.manager.repo.project.ProjectUserRepo;
import com.chinasoft.maysham.manager.request.InviteReq;
import com.chinasoft.maysham.manager.service.project.ProjectUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Collections;

@Slf4j
@Service
public class ProjectUserServiceImpl implements ProjectUserService {

    @Resource
    private ProjectRepo projectRepo;

    @Resource
    private ProjectUserRepo projectUserRepo;

    @Override
    public void initByProject(Project save, String userId) {
        ProjectUser projectUser = new ProjectUser(userId, save.getId(), true);
        projectRepo.save(projectUser);
    }

    @Override
    public ProjectUser invite(InviteReq inviteReq, String userId) {
        if (StringUtils.isEmpty(inviteReq.getProjectId()) || StringUtils.isEmpty(inviteReq.getUserId())) {
            throw new BizException("invalid param");
        }
        ProjectUser projectUser = projectUserRepo.findByUserIdAndProjectId(inviteReq.getUserId(), inviteReq.getProjectId());
        if (projectUser != null) {
            throw new BizException("no need to invite");
        }
        ProjectUser dbProjectUser = new ProjectUser(inviteReq.getUserId(), inviteReq.getProjectId(), false);
        Role role = projectUserRepo.findById(inviteReq.getRoleId(), Role.class);
        if (role != null) {
            dbProjectUser.setRoleIds(Collections.singletonList(role.getId()));
        }
        return projectUserRepo.save(dbProjectUser);
    }

    @Override
    public void unRegisterUser(String userId) {
        projectUserRepo.deleteUser(userId);
    }
}
